/**
 * 封装接口请求
 * @date     2021-07-13
 * @author   guojie
 */
import axios, { AxiosRequestConfig, AxiosResponse } from "axios"
import type {HttpResponse} from '../../types/http'

const service = axios.create({
    baseURL:import.meta.env.VITE_APP_BASE_API+'/testapi',
    timeout:5000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    }
})

// request interceptor
service.interceptors.request.use(
    (config:AxiosRequestConfig) => {
        // token信息存在时
        // if (store.getters.token) {
        // config.headers['Authorization'] = getToken()
        // }
        return config
    },
    error => {
        // 请求错误时
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use((response:AxiosResponse) => {
        const res = response.data
        if (response.config.responseType == 'blob') {
            return res
        }
        if (res.code !== 0) {
            // Message({
            //     message: res.msg || 'Error',
            //     type: 'error',
            //     duration: 5 * 1000
            // })

            // 登录已失效，需要重新登录
            if (res.code == 4) {
                // to re-login
                // store.dispatch('user/resetToken').then(() => {
                //     setTimeout(() => {
                //         location.reload()
                //     }, 800)
                // })
            }
            return Promise.reject(res)
        } else {
            return res
        }
    },
    error => {
        if (error && error.response) {
            switch (error.response.status) {
                case 400: error.message = '请求错误(400)'; break;
                case 401: error.message = '未授权,请登录(401)'; break;
                case 403: error.message = '拒绝访问(403)'; break;
                case 404: error.message = `请求地址出错: ${error.response.config.url}`; break;
                case 405: error.message = '请求方法未允许(405)'; break;
                case 408: error.message = '请求超时(408)'; break;
                case 500: error.message = '服务器内部错误(500)'; break;
                case 501: error.message = '服务未实现(501)'; break;
                case 502: error.message = '网络错误(502)'; break;
                case 503: error.message = '服务不可用(503)'; break;
                case 504: error.message = '网络超时(504)'; break;
                case 505: error.message = 'HTTP版本不受支持(505)'; break;
                default: error.message = `连接错误: ${error.message}`; 
            }
        } else {
            error.message = '连接到服务器失败，请联系管理员'
        };
        // Message({
        //     message: error.message,
        //     type: 'error',
        //     duration: 5 * 1000
        // })
        return Promise.reject(error)
    }
)

export default service